// EventBus header file
// Responsible for the communication between UI and board.

#ifndef ETB_EVENTBUS_H_
#define ETB_EVENTBUS_H_

#include <vector>
#include <set>
#include <deque>
#include <string>
#include <pthread.h>

namespace etb {

    // EventClient
    // Interface for event clients
    class EventClient {
    public:
      typedef struct {
        std::string target;
        std::string device;
        std::string param;
      } EventStruct;

    public:
      virtual void handleEvent(const std::string event) = 0;

    public:
      static void parseEvent(const std::string event, 
                             EventStruct* evts);
      static std::string makeCmd(const std::string target, 
                                 const std::string device, 
                                 const std::string param);
    };


    // EventBus
    // Responsible for the communication between UI and board.
    // SendEvent() will trigger an broadcasting of event 
    // to all the of clients, including the sender itself.
    class EventBus {

    // constructors and destructors
    public:
        EventBus();
        ~EventBus();

    // public api
    public:
        void registerEventClient(EventClient* client);
        void unregisterEventClient(EventClient* client);

        void sendEvent(const std::string event);

        // Start the event callback thread
        void start();
        // Stop the event callback thread
        void stop();

        // Thread entry point
        static void* threadEntry(void* arg);

    // inherited api
    public:

    // private methods
    private:
        void threadProc();
        void callbackAllClients(const std::string event);
        void makeTimespec(struct timespec* ts, int sec);

    // private members
    private:
        std::set<EventClient*>      clients_;
        std::deque<std::string>     queue_;
        bool                        running_;
        pthread_t         thread_;
        pthread_mutex_t   mutex_;
        pthread_cond_t    cond_;
    };
}

#endif  // ETB_EVENTBUS_H_
